package com.example.projectmanagement.service.study;

import com.example.projectmanagement.dto.study.CourseDto;
import com.example.projectmanagement.model.study.Course;
import com.example.projectmanagement.model.study.Module;
import com.example.projectmanagement.model.study.Lesson;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.repository.study.CourseRepository;
import com.example.projectmanagement.repository.study.ModuleRepository;
import com.example.projectmanagement.repository.study.LessonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ContentService {

    @Autowired
    private CourseRepository courseRepository;
    
    @Autowired
    private ModuleRepository moduleRepository;
    
    @Autowired
    private LessonRepository lessonRepository;

    /**
     * 创建课程
     */
    @Transactional
    public Course createCourse(Course course, User creator) {
        course.setCreator(creator);
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        return courseRepository.save(course);
    }

    /**
     * 更新课程
     */
    @Transactional
    public Course updateCourse(Long courseId, Course courseDetails) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        
        course.setTitle(courseDetails.getTitle());
        course.setDescription(courseDetails.getDescription());
        course.setCoverImage(courseDetails.getCoverImage());
        course.setDifficultyLevel(courseDetails.getDifficultyLevel());
        course.setEstimatedDuration(courseDetails.getEstimatedDuration());
        course.setCategory(courseDetails.getCategory());
        course.setSubcategory(courseDetails.getSubcategory());
        course.setTags(courseDetails.getTags());
        course.setStatus(courseDetails.getStatus());
        course.setUpdateTime(LocalDateTime.now());
        
        if ("ACTIVE".equals(course.getStatus()) && course.getPublishTime() == null) {
            course.setPublishTime(LocalDateTime.now());
        }
        
        return courseRepository.save(course);
    }

    /**
     * 获取课程分页列表
     */
    public Page<Course> getCourses(Pageable pageable) {
        return courseRepository.findAll(pageable);
    }

    /**
     * 根据状态获取课程分页列表
     */
    public Page<Course> getCoursesByStatus(String status, Pageable pageable) {
        return courseRepository.findByStatus(status, pageable);
    }

    /**
     * 根据分类获取课程分页列表
     */
    public Page<Course> getCoursesByCategory(String category, Pageable pageable) {
        return courseRepository.findByCategory(category, pageable);
    }

    /**
     * 根据分类和子分类获取课程分页列表
     */
    public Page<Course> getCoursesByCategoryAndSubcategory(String category, String subcategory, Pageable pageable) {
        return courseRepository.findByCategoryAndSubcategory(category, subcategory, pageable);
    }

    /**
     * 搜索课程
     */
    public Page<Course> searchCourses(String keyword, Pageable pageable) {
        return courseRepository.findByTitleContainingIgnoreCase(keyword, pageable);
    }

    /**
     * 获取已发布的课程
     */
    public Page<Course> getPublishedCourses(String category, String subcategory, String keyword, Pageable pageable) {
        return courseRepository.findPublishedCourses(category, subcategory, keyword, pageable);
    }

    /**
     * 根据ID获取课程
     */
    public Optional<Course> getCourseById(Long id) {
        return courseRepository.findById(id);
    }

    /**
     * 删除课程
     */
    @Transactional
    public void deleteCourse(Long id) {
        // 先删除相关的模块和课时
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + id));
        
        // 删除课程相关的模块和课时
        List<Module> modules = moduleRepository.findByCourseOrderByDisplayOrderAsc(course);
        for (Module module : modules) {
            lessonRepository.deleteByModule(module);
            moduleRepository.delete(module);
        }
        
        courseRepository.delete(course);
    }
    
    /**
     * 发布课程
     */
    @Transactional
    public Course publishCourse(Long id) {
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + id));
        
        // 设置课程状态为已发布
        course.setStatus("ACTIVE");
        course.setPublishTime(LocalDateTime.now());
        
        return courseRepository.save(course);
    }
    
    /**
     * 取消发布课程
     */
    @Transactional
    public Course unpublishCourse(Long id) {
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + id));
        
        // 设置课程状态为未发布
        course.setStatus("INACTIVE");
        course.setPublishTime(null);
        
        return courseRepository.save(course);
    }

    /**
     * 获取所有分类
     */
    public List<String> getAllCategories() {
        return courseRepository.findDistinctCategories();
    }

    /**
     * 根据分类获取所有子分类
     */
    public List<String> getSubcategoriesByCategory(String category) {
        return courseRepository.findDistinctSubcategoriesByCategory(category);
    }

    /**
     * 创建模块
     */
    @Transactional
    public Module createModule(Module module) {
        module.setCreateTime(LocalDateTime.now());
        module.setUpdateTime(LocalDateTime.now());
        return moduleRepository.save(module);
    }

    /**
     * 更新模块
     */
    @Transactional
    public Module updateModule(Long moduleId, Module moduleDetails) {
        Module module = moduleRepository.findById(moduleId)
                .orElseThrow(() -> new RuntimeException("Module not found with id: " + moduleId));
        
        module.setTitle(moduleDetails.getTitle());
        module.setDescription(moduleDetails.getDescription());
        module.setDisplayOrder(moduleDetails.getDisplayOrder());
        module.setUpdateTime(LocalDateTime.now());
        
        return moduleRepository.save(module);
    }

    /**
     * 根据课程获取模块列表
     */
    public List<Module> getModulesByCourse(Long courseId) {
        return moduleRepository.findByCourseIdOrderByDisplayOrderAsc(courseId);
    }

    /**
     * 根据ID获取模块
     */
    public Optional<Module> getModuleById(Long id) {
        return moduleRepository.findById(id);
    }

    /**
     * 删除模块
     */
    @Transactional
    public void deleteModule(Long id) {
        Module module = moduleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Module not found with id: " + id));
        
        // 先删除模块下的所有课时
        lessonRepository.deleteByModule(module);
        moduleRepository.delete(module);
    }

    /**
     * 创建课时
     */
    @Transactional
    public Lesson createLesson(Lesson lesson) {
        lesson.setCreateTime(LocalDateTime.now());
        lesson.setUpdateTime(LocalDateTime.now());
        return lessonRepository.save(lesson);
    }

    /**
     * 更新课时
     */
    @Transactional
    public Lesson updateLesson(Long lessonId, Lesson lessonDetails) {
        Lesson lesson = lessonRepository.findById(lessonId)
                .orElseThrow(() -> new RuntimeException("Lesson not found with id: " + lessonId));
        
        lesson.setTitle(lessonDetails.getTitle());
        lesson.setContent(lessonDetails.getContent());
        lesson.setLessonType(lessonDetails.getLessonType());
        lesson.setVideoUrl(lessonDetails.getVideoUrl());
        lesson.setDocumentUrl(lessonDetails.getDocumentUrl());
        lesson.setEstimatedDuration(lessonDetails.getEstimatedDuration());
        lesson.setDisplayOrder(lessonDetails.getDisplayOrder());
        lesson.setUpdateTime(LocalDateTime.now());
        
        return lessonRepository.save(lesson);
    }

    /**
     * 根据模块获取课时列表
     */
    public List<Lesson> getLessonsByModule(Long moduleId) {
        return lessonRepository.findByModuleIdOrderByDisplayOrderAsc(moduleId);
    }

    /**
     * 根据ID获取课时
     */
    public Optional<Lesson> getLessonById(Long id) {
        return lessonRepository.findById(id);
    }

    /**
     * 删除课时
     */
    @Transactional
    public void deleteLesson(Long id) {
        lessonRepository.deleteById(id);
    }

    /**
     * 获取课程的总课时数
     */
    public Long getTotalLessonsByCourse(Long courseId) {
        return lessonRepository.countByCourseId(courseId);
    }
    
    /**
     * 将Course实体转换为CourseDto
     */
    public CourseDto convertToDto(Course course) {
        CourseDto dto = new CourseDto();
        dto.setId(course.getId());
        dto.setTitle(course.getTitle());
        dto.setDescription(course.getDescription());
        dto.setCoverImage(course.getCoverImage());
        dto.setDifficultyLevel(course.getDifficultyLevel());
        dto.setEstimatedDuration(course.getEstimatedDuration());
        dto.setCategory(course.getCategory());
        dto.setSubcategory(course.getSubcategory());
        dto.setStatus(course.getStatus());
        dto.setCreateTime(course.getCreateTime());
        dto.setUpdateTime(course.getUpdateTime());
        dto.setPublishTime(course.getPublishTime());
        
        // 安全地处理tags集合
        try {
            if (course.getTags() != null) {
                dto.setTags(new ArrayList<>(course.getTags()));
            }
        } catch (Exception e) {
            dto.setTags(new ArrayList<>());
        }
        
        // 设置创建者信息
        if (course.getCreator() != null) {
            dto.setCreatorId(course.getCreator().getId());
            dto.setCreatorName(course.getCreator().getName());
        }
        
        return dto;
    }
}